package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author itheima
 * @Date 2023-07-17 17:34
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserLogin(UserLoginDTO userLoginDTO) {
        //获取openid
        String openid = getOpenid(userLoginDTO.getCode());
        //判断openid是否有效
        if (openid==null){
            throw  new UserNotLoginException(MessageConstant.USER_NOT_LOGIN);
        }
        //根据openid查询用户
             User user= userMapper.getByUser(openid);

        //判断用户数据库是否记录
        if (user==null){
            //没有记录创建实体类
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //插入数据库 记录
            userMapper.insertUser(user);
        }
        //返回
        return user;
    }
    @Autowired
    private  WeChatProperties  weChatProperties;

    private String getOpenid(String  code){
        //小程序登录调用路径
        String url ="https://api.weixin.qq.com/sns/jscode2session";
        //创建map存入数据
        Map<String, String> map = new HashMap<>();
        //小程序appid
        map.put("appid", weChatProperties.getAppid());
        //小程序密钥
        map.put("secret", weChatProperties.getSecret());
        //前端拿到的code
        map.put("js_code", code);
        //约定好写死了authorization_code
        map.put("grant_type", "authorization_code");
        //3.使用工具类HttpClientUtil的doGet发送请求并返回json结果
        String result = HttpClientUtil.doGet(url, map);
        //通过工具类JSONObject的格式
        JSONObject jsonObject = JSONObject.parseObject(result);
        //解析出openid
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
